package com.spzx.test.t9;

import lombok.SneakyThrows;
import org.apache.commons.lang3.RandomUtils;
import org.apache.poi.ss.formula.functions.T;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Screen {

    Object content = null;

    ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    @SneakyThrows
    public void test(){

        ReentrantReadWriteLock.ReadLock readLock = lock.readLock();// 读锁，排斥写，不排斥读
        ReentrantReadWriteLock.WriteLock writeLock2 = lock.writeLock();// 写锁,排斥读写

        readLock.lock();
        writeLock2.lock();

        System.out.println(Thread.currentThread().getName()+"正在尝试读取屏幕1");
        TimeUnit.SECONDS.sleep(3);

        System.out.println(Thread.currentThread().getName()+"正在尝试读取屏幕2");
        TimeUnit.SECONDS.sleep(3);

        readLock.unlock();
        writeLock2.unlock();

    }

    @SneakyThrows
    public void writeContent(Object o){
        lock.writeLock().lock();
        System.out.println(Thread.currentThread().getName()+"正在写入屏幕");
        this.content = o;
        TimeUnit.SECONDS.sleep(RandomUtils.nextInt(1,5));
        System.out.println(Thread.currentThread().getName()+"写入完成："+content);
        lock.writeLock().unlock();
    }

    @SneakyThrows
    public Object readContent(){
        lock.readLock().lock();
        System.out.println(Thread.currentThread().getName()+"正在读取屏幕");
        TimeUnit.SECONDS.sleep(RandomUtils.nextInt(1,5));
        System.out.println(Thread.currentThread().getName()+"读取完成：");
        lock.readLock().unlock();
        return content;
    }

}
